<template>
  <div class="hello">
    <h3>composition-api: {{ user }}</h3>
    <input type="number" v-model="searchQuery">
    <ul>
      <li>list: </li>
      <li v-for="item in list" :key="item">{{ item }}</li>
    </ul>
    <ul>
      <li>match: </li>
      <li v-for="item in matchingList" :key="`${item}aaa`">{{ item }}</li>
    </ul>
    <div id="effect"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, toRefs, ref, watchEffect, onRenderTracked } from 'vue'
import HelloWorldCompList from '@/composables/HelloWorldCompList'
import HelloWorldCompListFilter from '@/composables/HelloWorldCompListFilter'
export default defineComponent({
  name: 'HelloWorldComposition',
  props: {
    user: Number
  },
  // composition api【函数式组合api】在created之前执行, 里面注册的钩子函数会比选项API上的钩子早执行
  setup (props, context) {
    console.log('context 可解构：', context)
    // props是响应式，不能使用ES6解构，会消除响应式 ===》使用toRefs
    const { user } = toRefs(props)

    const { list, getList } = HelloWorldCompList(user)

    const { searchQuery, matchingList } = HelloWorldCompListFilter(list)

    // 暴露组件内方法给到父组件ref引用== start ==
    const { expose } = context
    const count = ref(0)
    const increment = () => ++count.value
    expose({
      increment
    })
    // 暴露组件内方法给到父组件ref引用== end ==

    // onRenderTracked((event) => {
    //   debugger
    // })

    // 副作用===DOM更新
    const countNumber = ref(0)
    watchEffect(() => {
      // document.getElementById('effect')?.innerHTML = `计数：${countNumber}`
      console.log(`副作用计数：${countNumber.value}`)
    })
    countNumber.value++

    return {
      list,
      getList,
      searchQuery,
      matchingList
    }
  },
  watch: {
    user: function (n) {
      console.log('new value: ', n)
      this.instanceMethod()
    }
  },
  mounted () {
    console.log('helloworld mounted > user props: ', this.user)
  },
  methods: {
    instanceMethod () {
      console.log('HELLO WORLD COMPOSITION')
    }
  }
})
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
h3
  margin 10px 0 0

input
  margin: 10px 0

ul
  list-style-type none
  padding 0
  text-align left

li
  display inline-block
  margin 0 10px

a
  color #42b983
</style>
